package pe.upc.dsd.jjjar.metropolitano;

import java.util.ArrayList;
import java.util.List;

import pe.upc.dsd.jjjar.metropolitano.services.RequestMethod;
import pe.upc.dsd.jjjar.metropolitano.services.RestClient;
import pe.upc.dsd.jjjar.rest.informacion.Estacion;
import pe.upc.dsd.jjjar.rest.informacion.Response;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Point;
import android.os.Bundle;
import android.view.View;
import android.view.ViewGroup.LayoutParams;
import android.widget.LinearLayout;

import com.google.android.maps.GeoPoint;
import com.google.android.maps.MapActivity;
import com.google.android.maps.MapController;
import com.google.android.maps.MapView;
import com.google.android.maps.Overlay;
import com.google.gson.Gson;
import com.google.gson.JsonParseException;

public class RutasInMapActivity extends MapActivity {

	MapView mapView;
	MapController mc;
	GeoPoint p;

	List<String[]> rutas = new ArrayList<String[]>();

	class MapOverlay extends com.google.android.maps.Overlay {

		private GeoPoint p;

		public MapOverlay(GeoPoint p) {
			this.p = p;
		}

		@Override
		public boolean draw(Canvas canvas, MapView mapView, boolean shadow,
				long when) {
			super.draw(canvas, mapView, shadow);

			// ---translate the GeoPoint to screen pixels---
			Point screenPts = new Point();
			mapView.getProjection().toPixels(p, screenPts);

			// ---add the marker---
			Bitmap bmp = BitmapFactory.decodeResource(getResources(),
					R.drawable.pushpin_estacion);
			canvas.drawBitmap(bmp, screenPts.x - 14, screenPts.y - 42, null);
			return true;
		}

	}

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.rutasmaps);

		Bundle extra = getIntent().getExtras();
		String bus = extra.getString("bus");

		RestClient client = new RestClient(
				Constantes.SERVER_ENDPOINT + "/Informacion/rest/info/buses/" + bus);
		try {
			client.Execute(RequestMethod.GET);
		} catch (Exception e) {

		}

		String response = client.getResponse();

		Gson gson = new Gson();
		Response responseObject = null;

		try{
			responseObject = gson.fromJson(response, Response.class);
		}catch(JsonParseException e){}

		if (responseObject != null) {

			final List<Estacion> estaciones = responseObject.getListEstacion();
			for (Estacion estacion : estaciones) {
				rutas.add(new String[] {
						String.valueOf(estacion.getPosicion().getLatitud()),
						String.valueOf(estacion.getPosicion().getLongitud()) });
			}

			mapView = (MapView) findViewById(R.id.mapView);
			LinearLayout zoomLayout = (LinearLayout) findViewById(R.id.zoom);
			View zoomView = mapView.getZoomControls();

			zoomLayout.addView(zoomView, new LinearLayout.LayoutParams(
					LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));
			mapView.displayZoomControls(true);

			boolean show = false;
			mc = mapView.getController();

			List<Overlay> listOfOverlays = mapView.getOverlays();
			listOfOverlays.clear();

			for (String[] coordinates : rutas) {

				double lat = Double.parseDouble(coordinates[0]);
				double lng = Double.parseDouble(coordinates[1]);

				p = new GeoPoint((int) (lat * 1E6), (int) (lng * 1E6));

				// ---Add a location marker---
				MapOverlay mapOverlay = new MapOverlay(p);
				listOfOverlays.add(mapOverlay);
			}

			mc.animateTo(p);
			mc.setZoom(17);

		} else {

			AlertDialog.Builder builder = new AlertDialog.Builder(
					RutasInMapActivity.this);
			builder.setMessage(
					"Se produjo un error en la comunicacion con el WebService.")
					.setCancelable(false)
					.setPositiveButton("Yes",
							new DialogInterface.OnClickListener() {
								public void onClick(DialogInterface dialog,
										int id) {
									RutasInMapActivity.this.finish();
								}
							})
					.setNegativeButton("No",
							new DialogInterface.OnClickListener() {
								public void onClick(DialogInterface dialog,
										int id) {
									dialog.cancel();
								}
							});
			AlertDialog alert = builder.create();

		}

		mapView.invalidate();

	}

	@Override
	protected boolean isRouteDisplayed() {
		return false;
	}

}
